package io.gitee.tianhaoran.chat.common.entity;

import cn.hutool.core.lang.Assert;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.gitee.tianhaoran.chat.common.exception.ErrorCode;
import io.gitee.tianhaoran.chat.common.exception.ServiceException;
import io.gitee.tianhaoran.chat.common.exception.enums.GlobalErrorCodeConstants;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * <p>
 * 作者：沈自在
 **/
@Data
public class Result<T> implements Serializable {

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 返回数据
     */
    private T data;

    /**
     * 错误提示，用户可阅读
     */
    private String msg;

    /**
     *
     */
    public static <T> Result<T> error(Result<?> result) {
        return error(result.getCode(), result.getMsg());
    }

    /**
     *
     */
    public static <T> Result<T> error(Integer code, String message) {
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code 必须是错误的！");
        Result<T> result = new Result<>();
        result.code = code;
        result.msg = message;
        return result;
    }

    /**
     *
     */
    public static <T> Result<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }

    /**
     *
     */
    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = "";
        return result;
    }

    /**
     *
     */
    public static boolean isSuccess(Integer code) {
        return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode());
    }

    /**
     *
     */
    @JsonIgnore
    public boolean isSuccess() {
        return isSuccess(code);
    }

    /**
     *
     */
    @JsonIgnore
    public boolean isError() {
        return !isSuccess();
    }

    /**
     *
     */
    public void checkError() throws ServiceException {
        if (isSuccess()) {
            return;
        }
        // 业务异常
        throw new ServiceException(code, msg);
    }

    /**
     *
     */
    @JsonIgnore
    public T getCheckedData() {
        checkError();
        return data;
    }

    /**
     *
     */
    public static <T> Result<T> error(ServiceException serviceException) {
        return error(serviceException.getCode(), serviceException.getMessage());
    }
}
